import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'
import {useStorage} from '@vueuse/core'
import {serverManager, serverToken} from '@/stores/modules/mabager.js'


const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login/LoginPage.vue')
    },
    {
        path: '/',
        name: 'main',
        component: () => import('../views/layout/LayoutContainer.vue')
    },
    {
        path: '/404',
        name: 'NotFound',
        component: () => import('@/views/not_found/404.vue')
    },
    {
        path: '/:pathMatcher(.*)*',
        redirect: '/404'
    }
]

const router = createRouter({
    history: createWebHashHistory(), // 路径格式
    routes: routes // 路由数组
})

// 登录访问拦截
router.beforeEach((to, from) => {
    if ((to.name === 'main' && !serverToken.value)) {
        return '/login'
    }

})

//修改路由标题
router.afterEach((to, from) => {
     (to)
    document.title = to.name?.toString()
})

export const serverMenus = useStorage("serverMenus", [])
const serverRoutes = useStorage('serverRoutes', [])
addServerRoutes(serverRoutes.value)

//添加路由信息
export function addServerRoutes(routeList) {
 
    
    for (const r of routeList) {
        router.addRoute('main', {
            path: r.path,
            name: r.name,
            component: () => import(/* @vite-ignore */r.component)
        })
    }
    serverRoutes.value = routeList
}

//重置路由、token、菜单、权限、人员信息
export function resetRouter() {
    for (const r of routes) {
        router.addRoute(r)
    }
    serverRoutes.value = null;
    serverMenus.value = null;
    serverManager.value = null;
    serverToken.value = null;
}

export default router
